// subtool/pages/action/index/index.js
let text = require('../../../../common/util/text.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    xPageReady:false,
    current:0,
    week:'',
    today_pressure_source_status:'',
    treatment_item_id:'',
    type:'',
    pressure_source_name:'',//压力源名称
    solution:[],
    step:1,
    _id:'',
    currentStep:1
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
      let that =this;
      that.setData({
        week:Number(options.week),
        treatment_item_id:options.treatment_item_id,
        type:Number(options.type),
        today_pressure_source_status: options.today_pressure_source_status =='true'?true:false,
        xPageReady:options.today_pressure_source_status =='true'?true:false
      })
      that.xGetHelp()
      that.xToPracticeStatus()
  },
  onShow() {
    getApp().globalData.lock=false
    this.xInit()
    this.xGetlist()
  },
  xChildReload: function () {
    var pages = getCurrentPages();
    if (pages.length > 1) {
      var beforePage = pages[pages.length - 2];
      beforePage.xInfo();
    }
  },
  xInit:function(week,id){
    let that =this;
    wx.cloud.callFunction({
      name: 'pressure_source_analysis',
      data: {
        action: "get_pressure_source"
      }
    }).then(res => {
      if(res.result.length>0 && that.data.today_pressure_source_status == true ){
          let data= res.result[res.result.length-1]
          that.setData({
            _id:data._id,
            pressure_source_name:data.pressure_source_name,
            solution:data.solution,
            step:4,
            currentStep:4
          })
          that.sortSolution()
      }else{
        let arr =[]
        for(var i =0;i<3;i++){
          let obj = {
            name:'',
            pros_cons:'',
            advantage_score:0,
            shortcoming_score:0,
            total_score:0,
            is_feasible:-1
          }
          arr.push(obj)
        }
        const pressure_source_name = wx.getStorageSync('pressure_source_name')
        that.setData({
          pressure_source_name:pressure_source_name
        })
        const solution = wx.getStorageSync('solution')
        that.setData({
          solution:solution.length>0 ? solution : arr
        })
      }
    })
  },
  xAlign:function(){
    let that = this
    let value = wx.getStorageSync('solution')
    let name = wx.getStorageSync('pressure_source_name')
    let arr =[]
    for(var i =0;i<3;i++){
      let obj = {
        name:'',
        pros_cons:'',
        advantage_score:0,
        shortcoming_score:0,
        total_score:0,
        is_feasible:-1
      }
      arr.push(obj)
    }
    that.setData({
      step:1,
      currentStep:1,
      current:0,
      solution:value.length > 0 ? value : arr,
      pressure_source_name: name?name:''
    })
  },
  xGetlist:function(){
    let that =this;
    wx.cloud.callFunction({
      name: 'pressure_source_analysis',
      data: {
        action: "get_pressure_source_by_diary"
      }
    }).then(res => {
      that.setData({
        list:res.result
      })
    })
  },
  xToProce:function(){
    this.setData({
      show:false,
      page_show:false
    })
  },
  xTonext:function(){
    let that =this;
    if(that.data.step==1){
      if(that.data.pressure_source_name == ''){
        wx.showModal({
          title: "提示",
          content: "请输入困扰你的问题",
          showCancel: false,
          confirmText:'好的'
        })
        return
      }
    }else if(that.data.step==2){
      let key =0
      for(let index in that.data.solution){
        if(that.data.solution[index].name ==''){
          key=key+1
        }
      }
      if(key>0){
        wx.showModal({
          title: "提示",
          content: "请确保所有内容填写正确，当前有"+ key +"项内容未填写，请检查！",
          showCancel: false,
          confirmText:'好的'
        })
        return
      }
    }else if(that.data.step==3){
      let num = 0 
      for(let index in that.data.solution){
        if(that.data.solution[index].advantage_score ==0  || that.data.solution[index].shortcoming_score ==0 || that.data.solution[index].pros_cons == ''){
          num=num+1
        }
      }
      if(num>0){
        wx.showModal({
          title: "提示",
          content: "请确保所有内容填写正确，当前有"+ key +"项内容未填写，请检查！",
          showCancel: false,
          confirmText:'好的'
        })
        return
      }
    }
    that.setData({
      step:that.data.step+1,
      currentStep:that.data.step+1
    })
    wx.pageScrollTo({
      scrollTop:0
    })
  },
  xCheckInput:function(e){
    // var sensitiveWords = ['杀人', '屎', '刀人'];  
    // for (var i = 0; i < sensitiveWords.length; i++) {
    //   var regex = new RegExp(sensitiveWords[i], 'gi');  // 创建不区分大小写的正则表达式
    //   if (regex.test(e.detail.value)) {
    //     wx.showToast({
    //       title: ‘word_filter',
    //       icon:'none'
    //     })
    //   }
    // }
    this.setData({
      pressure_source_name:e.detail.value
    })
    wx.setStorageSync('pressure_source_name', e.detail.value)
  },
  xSetStep:function(e){
    let that = this
    let params = e.currentTarget.dataset
    if(params.index+1 <= that.data.currentStep ){
      that.setData({
        step:params.index+1
      })
    }
  },
  // 是否可行
  xSetIsFeasible:function(e){
    let that = this
    let params = e.currentTarget.dataset
    this.setData({
      [`solution[${params.index}].is_feasible`]: params.is_feasible,
      [`solution[${params.index}].advantage_score`]: 0,
      [`solution[${params.index}].shortcoming_score`]: 0,
      [`solution[${params.index}].total_score`]: 0,
    })
    wx.setStorageSync('solution', that.data.solution)
  },
  // 下一个解决方案解析
  xNextSolution:function(){
    let that = this
    if(that.data.step ==3){
      if(!that.validation() ){
        return
      } 
    }
    that.setData({
      current :that.data.current+1
    })
    wx.pageScrollTo({
      scrollTop:0
    })
  },
  // 上一个解决方案
  xBackSolution:function(){
    let that = this
    that.setData({
      current :that.data.current-1
    })
    wx.pageScrollTo({
      scrollTop:0
    })
  },
  // 非空校验
  validation:function(){
    let that = this
    let num = 0 
    let index = that.data.current
    if(that.data.solution[index].is_feasible == -1 || that.data.solution[index].is_feasible == undefined ){
      num = num+1
    }
    if( that.data.solution[index].is_feasible == true ){
      if(that.data.solution[index].advantage_score ==0  || that.data.solution[index].shortcoming_score ==0){
        num = num+1
      }
    }
    if(num>0){
      wx.showModal({
        title: "提示",
        content: "请确保所有内容填写正确，当前有内容未填写，请检查！",
        showCancel: false,
        confirmText:'好的'
      })
      return false
    }else {
      return true
    }
  },
  // 设置评分
  xSetScore:function(e){
    let params = e.currentTarget.dataset
    this.setData({
      [`solution[${params.index}].${params.type}`] : params.i+1,
      
    })
    this.setData({
      [`solution[${params.index}].total_score`] : this.data.solution[params.index].advantage_score + (0-this.data.solution[params.index].shortcoming_score)
    })
    wx.setStorageSync('solution', this.data.solution)
  },
  // 新增方案
  xToaddsolution:function(){
    let that =this;
    let obj = {
      advantage_score: 0,
      name: "",
      pros_cons: "",
      shortcoming_score: 0,
      total_score: 0,
      is_feasible:-1
    }
    let arr = that.data.solution
    arr.push(obj)
    that.setData({
      solution:arr
    })
  },
  // 设置方案
  bindInput:function(e){
    let that =this;
    let index = e.currentTarget.dataset.index
    that.setData({
      [`solution[${index}].name`]:e.detail.value,
    })
    wx.setStorageSync('solution', that.data.solution)
  },
  // 优缺点
  bindInputProsCons:function(e){
    let that =this;
    let index = e.currentTarget.dataset.index
    that.setData({
      [`solution[${index}].pros_cons`]:e.detail.value,
    })
    wx.setStorageSync('solution', that.data.solution)
  },
   // 删除某条
  xTodelete:function(e){
    let that =this;
    let index  =e.currentTarget.dataset.index
    let data = this.data.solution
    data.splice(index,1)
    that.setData({
      solution:data
    })
    wx.setStorageSync('solution', that.data.solution)
  },
  xSave:function(){
    let that =this;
    if(getApp().globalData.lock==true){
      return
    }
    if(!that.validation() ){
      return
    }
    let _dataObj = {
      treatment_item_id:that.data.treatment_item_id,//任务id
      week:that.data.week,//第几个任务
      pressure_source_name:that.data.pressure_source_name,
      solution: that.data.solution
    }
    getApp().globalData.lock=true
    if(that.data.today_pressure_source_status==true){
      _dataObj._id = that.data._id
      that.xToUpdate(_dataObj)
    }else{
      that.xToAdd(_dataObj)
    }
    that.setData({
      step:that.data.step + 1 ,
      currentStep:that.data.step+1,
      current:0
    }) 
    wx.pageScrollTo({
      scrollTop:0
    })
    that.sortSolution()
  },
  sortSolution:function(){
    let that = this
    let arr = JSON.parse(JSON.stringify(that.data.solution));
    arr.sort((a, b) => {
      return b.total_score - a.total_score;
    });
    that.setData({
      sortList: arr
    })
  },
  xToUpdate:function(_dataObj){
    let that =this;
    wx.cloud.callFunction({
      name: 'pressure_source_analysis',
      data: {
        action: "update_pressure_source",
        dataObj: _dataObj
      }
    }).then(res => {
      getApp().globalData.lock=false
      that.xChildReload()
      wx.setStorageSync('solution', [])
      wx.setStorageSync('pressure_source_name', '')
    }).catch(err=>{
      getApp().globalData.lock=false
    })
  },
  xToAdd:function(_dataObj){
    let that =this;
    wx.cloud.callFunction({
      name: 'pressure_source_analysis',
      data: {
        action: "add_pressure_source",
        dataObj: _dataObj
      }
    }).then(res => {
      getApp().globalData.lock=false
      that.xChildReload()
      wx.setStorageSync('solution', [])
      wx.setStorageSync('pressure_source_name', '')
    }).catch(err=>{
      getApp().globalData.lock=false
    })
  },
  xToPracticeStatus:function(){
    let that =this;
    wx.cloud.callFunction({
      name: 'practice_help',
      data: {
        action: "get_practice_help_status",
        dataObj: {
          num:10
        }
      }
    }).then(res => {
      for(let index in res.result){
        if(res.result[index]._id==1){
          that.setData({
            PracticeStatus:res.result[index].status
          })
        }
      }
    })
  },
  xSet:function(){
      this.setData({
        xPageReady:true
      })
      wx.pageScrollTo({
        duration: 0,
        scrollTop:0
      })
  },
  xGetHelp:function(){
      let that=this;
      let _dataObj = {
        num:10,//练习任务类型数值
        type:1,//1:练习说明
      }
      wx.cloud.callFunction({
        name: 'practice_help',
        data: {
          action: "get_practice_help",
          dataObj: _dataObj
        }
      }).then(res => {
        res.result[0].content=text.text(res.result[0].content)
          this.setData({
            practice_help:res.result[0]
          })
      })
  },
  xTosetM:function(){
    wx.setStorageSync(this.data.treatment_item_id, this.data.treatment_item_id)
    this.setData({
      showtips:true,
      page_show:true,
      show:false
    })
  },
  xBack:function(){
    wx.navigateBack({
      delta:1
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})